<template>
    <div class="user-information">
        <van-nav-bar
            class="user-information__navbar"
            title="个人资料"
            left-arrow
            fixed
            :border="false"
            @click-left="onLeftClick"
        />
        <div class="user-information__head">
            <div class="user-information__avatar">
                <van-uploader v-model="fileList" :preview-image="false" :after-read="_afterRead">
                    <img :src="avatar ? avatar.content : userinfo.avatar" alt="">
                    <van-icon class-prefix="fa fa-camera"/>
                </van-uploader>
            </div>
        </div>
        <van-cell-group>
            <van-cell title="真实姓名" :value="userinfo.truename ? userinfo.truename : '未设置'" is-link
                      @click="_showDialog('truename')"/>
            <van-cell title="昵称" :value="userinfo.nickname ? userinfo.nickname : '未设置'" is-link
                      @click="_showDialog('nickname')"/>
            <van-cell title="性别" :value="sex || userSex" is-link @click="sheetShow = true"/>
            <van-cell title="QQ" :value="userinfo.qq ? userinfo.qq : '未设置'" is-link @click="_showDialog('qq')"/>
            <van-cell title="邀请码" :value="userinfo ? userinfo.refcode : '--'"/>
            <van-cell title="生日" :value="birthday || (userinfo.birthday ? userinfo.birthday : '未设置')" is-link
                      @click="popupShow = true"/>
        </van-cell-group>
        <van-field
            v-model="introduction"
            rows="2"
            autosize
            label="简介"
            type="textarea"
            maxlength="50"
            placeholder="请输入个人简介"
            show-word-limit
        />
        <div class="user-information__btn">
            <van-button round type="info" block @click="_submit">保存资料</van-button>
        </div>
        <van-dialog v-model="show" :title="titleText" show-cancel-button :beforeClose="_beforeClose">
            <van-field v-model="fieldValue" :placeholder="placeholderText"/>
        </van-dialog>
        <van-action-sheet
            v-model="sheetShow"
            :actions="actions"
            cancel-text="取消"
            @cancel="sheetShow = false"
            @select="_select"
        />
        <van-popup
            v-model="popupShow"
            position="bottom"
        >
            <van-datetime-picker
                v-model="currentDate"
                type="date"
                :max-date="maxDate"
                :min-date="minDate"
                @cancel="popupShow = false"
                @confirm="_getDate"
            />
        </van-popup>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
    name: 'user-information',
    data () {
        return {
            introduction: '',
            show: false,
            fieldValue: '',
            titleText: '',
            placeholderText: '',
            formData: {},
            fieldName: '',
            fileList: [],
            avatar: null,
            sheetShow: false,
            actions: [
                { name: '保密' },
                { name: '男' },
                { name: '女' }
            ],
            sex: null,
            popupShow: false,
            currentDate: new Date(1995, 4, 28),
            maxDate: '',
            minDate: '',
            birthday: null
        }
    },
    computed: {
        ...mapGetters(['userinfo']),
        userSex () {
            if (this.userinfo.sex === 0) {
                return '保密'
            } else {
                return this.userinfo.sex === 1 ? '男' : '女'
            }
        }
    },
    created () {
        console.log(this.userinfo)
        this.introduction = this.userinfo.desc
        const newDate = new Date()
        this.maxDate = new Date(newDate.setTime(newDate.getTime() - 24 * 60 * 60 * 1000))
        this.minDate = new Date(newDate.setFullYear(newDate.getFullYear() - 100))
        const _date = this.userinfo.birthday.split('-')
        if (_date.length) {
            this.currentDate = new Date(_date[0], _date[1] - 1, _date[2])
        }
        // switch (this.userinfo.sex) {
        //   case 1:
        //     this.actions[1]['color'] = 'red'
        //     break
        //   case 2:
        //     this.actions[2]['color'] = 'red'
        //     break
        //   default:
        //     this.actions[0]['color'] = 'red'
        // }
    },
    methods: {
        _beforeClose (action, done) {
            if (action === 'confirm') {
                if (!this.fieldValue) {
                    done(false)
                    return this.$toast('内容不能为空')
                }
                this.userinfo[this.fieldName] = this.fieldValue
                this.formData[this.fieldName] = this.fieldValue
                done()
            } else {
                done()
            }
        },
        _showDialog (type) {
            this.fieldName = type
            this.fieldValue = this.userinfo[type]
            switch (type) {
            case 'truename':
                this.titleText = '设置真实姓名'
                this.placeholderText = '请输入您的真实姓名'
                break
            case 'nickname':
                this.titleText = '设置用户昵称'
                this.placeholderText = '请输入您的用户昵称'
                break
            default:
                this.titleText = '设置QQ号码'
                this.placeholderText = '请输入您的QQ号码'
            }
            this.show = true
        },
        _submit () {
            this.$toast.loading({
                message: '保存中...',
                forbidClick: true,
                duration: 0
            })
            if (this.avatar) {
                let _formData = new FormData()
                _formData.append('file', this.avatar.file)
                this.$http.common.uploadImg(_formData).then(({ code, data }) => {
                    if (code === 200) {
                        this._setUser(data.img_url)
                    }
                })
            } else {
                this._setUser()
            }
        },
        _setUser (avatar) {
            if (this.introduction) {
                this.formData['desc'] = this.introduction
            }
            const _formData = avatar ? { ...this.formData, avatar } : this.formData
            this.$http.user.infomation(_formData).then(({ code, msg }) => {
                if (code === 200) {
                    this.$toast.success(msg)
                    this.$store.dispatch('getUser')
                    this.formData = {}
                }
            })
        },
        onLeftClick () {
            if (Object.keys(this.formData).length || this.introduction !== this.userinfo.desc) {
                this.$dialog.confirm({
                    title: '提示',
                    message: '您有修改的内容未保存，是否离开？'
                }).then(() => {
                    this.$router.go(-1)
                }).catch(() => {
                    // on cancel
                })
            } else {
                this.$router.go(-1)
            }
        },
        _afterRead () {
            this.avatar = this.fileList[0]
            this.fileList = []
        },
        _select (active, index) {
            this.formData['sex'] = index
            if (index === 0) {
                this.sex = '保密'
            } else if (index === 1) {
                this.sex = '男'
            } else {
                this.sex = '女'
            }
            this.sheetShow = false
        },
        _getDate (date) {
            const month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
            const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
            this.formData['birthday'] = `${date.getFullYear()}-${month}-${day}`
            this.birthday = this.formData.birthday
            this.popupShow = false
        }
    }
}
</script>

<style lang="scss">
.user-information {
    &__navbar {
        background: transparent;

        .van-icon {
            color: #ffffff;
        }

        .van-nav-bar__title {
            color: #ffffff;
        }
    }

    &__avatar {
        position: relative;

        i {
            position: absolute;
            left: 50%;
            transform: translate(-50%, 0);
            color: #ffffff;
            font-size: 20px;
            bottom: 0;
        }
    }

    &__head {
        background-image: linear-gradient(to top, #4481eb 0%, #04befe 100%);
        height: 220px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding-top: 25px;

        img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
        }
    }

    &__btn {
        padding: 40px 20px 20px;
    }
}
</style>
